﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Security.Cryptography;
using System.Collections;
using System.Collections.Specialized;

namespace Enterprise.Utility
{
    public static class StringExtend
    {

        #region "加解密"
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string MD5(this string input)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(input, "MD5");
        }

        /// <summary>
        /// SHA1加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string SHA1(this string input)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(input, "SHA1");
        }
        /// <summary>
        /// URL加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string UrlEncode(this string input)
        {
            return System.Web.HttpContext.Current.Server.UrlEncode(input);
        }

        /// <summary>
        /// URL解密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string UrlDecode(this string input)
        {
            return System.Web.HttpContext.Current.Server.UrlDecode(input);
        }

        /// <summary>
        /// 标准HTML编码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string HtmlEncode(this string str)
        {
            return System.Web.HttpContext.Current.Server.HtmlEncode(str);
        }
        /// <summary>
        /// 标准HTML解码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string HtmlDecode(this string str)
        {
            return System.Web.HttpContext.Current.Server.HtmlDecode(str);
        }

        #endregion

        #region "字符串处理"

        /// <summary>
        /// 清除HTML标签
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string ClearHTMLCode(this string input)
        {
            return input.ClearHTMLCode(false);
        }

        /// <summary>
        /// 清除HTML标签
        /// </summary>
        /// <param name="input"></param>
        /// <param name="isStrong">是否处理头尾的半标签</param>
        /// <returns></returns>
        public static string ClearHTMLCode(this string input, bool isStrong)
        {
            System.Text.RegularExpressions.Regex reg = new Regex("<[^>]+>");
            string result = reg.Replace(input, "");

            //第一步进行简单过滤
            //简单过滤后，头尾可能会残留部分代码。如果需要，截取掉，否则直接返回  如：  font>http://www.jdyou.com</a   
            if (string.IsNullOrEmpty(result) || (!isStrong))
                return result;

            try
            {
                int tmpindex = result.IndexOf(">") + 1;
                if (tmpindex > 0 && tmpindex < result.Length)
                {
                    result = result.Substring(tmpindex);
                }
                tmpindex = result.IndexOf("<");
                if (tmpindex >= 0)
                {
                    result = result.Substring(0, tmpindex);
                }
            }
            catch
            {
            }
            return result;
        }
        /// <summary>
        /// 获取截取后的邮箱
        /// </summary>
        /// <param name="intput"></param>
        /// <returns></returns>
        public static string GetEmail(this string intput) {
            return GetEmail(intput, 3);
        }
        /// <summary>
        /// 获取截取后的邮箱
        /// </summary>
        /// <param name="intput"></param>
        /// <returns></returns>
        public static string GetEmail(this string intput, int length)
        {
            string[] emaillist= intput.Split('@');
            if (emaillist.Length > 1) {
                StringBuilder reStr = new StringBuilder();
                if (emaillist[0].Length > length) {
                    reStr.Append(emaillist[0].Substring(0, emaillist[0].Length - length));
                    for (int i = 0; i < length; i++) reStr.Append("*");
                } else {
                    for (int i = 0; i < emaillist[0].Length; i++) reStr.Append("*");
                }
                reStr.Append("@" + emaillist[1]);
                return reStr.ToString();
            } else {
                return intput;
            }
        }
        /// <summary>
        /// 获取截取后的电话号码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string GetPhone(this string input)
        {
            if (input.Length > 7)
            {
                return input.Substring(0, 3) + "****" + input.Substring(7);
            }
            else
            {
                return "";
            }
        }
        /// <summary>
        /// 转换成键值的方式
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static NameValueCollection ToQueryString(this string input)
        {
            NameValueCollection nv = new NameValueCollection();
            if (string.IsNullOrEmpty(input)) return nv;
            string[] tmparr = input.Split('&');
            foreach (string atmpstr in tmparr)
            {
                if (!string.IsNullOrEmpty(atmpstr))
                {
                    string[] tmpkeyvalue = atmpstr.Split('=');
                    if (tmpkeyvalue.Length == 2)
                    {
                        string key = tmpkeyvalue[0].Trim();
                        string value = tmpkeyvalue[1].Trim().UrlDecode();
                        if (!string.IsNullOrEmpty(key))
                        {
                            nv[key] = value;
                        }
                    }
                }
            }
            return nv;
        }

        #endregion

        /// <summary>
        /// 将ID列表转为集合
        /// </summary>
        /// <param name="input"></param>
        /// <param name="separator"></param>
        /// <returns></returns>
        public static IList<int> ToIdList(this string input, char separator, bool ifemptythrowex)
        {
            string[] tmp = input.Split(separator);
            IList<int> result = new List<int>();
            foreach (string str in tmp)
            {
                result.Add(Convert.ToInt32(str));
            }
            if (ifemptythrowex && result.Count == 0)
            {
                throw new Exception("Ilist 为空！");
            }
            return result;
        }

        #region "数据格式验证"

        /// <summary>
        /// 是不是汉字
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsChineseCharacter(this string input)
        {
            string regstr = "^[\u4e00-\u9fa5]{0,}$";
            Regex reg = new Regex(regstr);
            return reg.IsMatch(input);
        }

        /// <summary>
        /// 判断是否是合法用户名
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsUserName(this string input)
        {
            Regex reg = new Regex(@"^([0-9a-zA-Z_]{3,30})$");
            return reg.IsMatch(input);
        }

        /// <summary>
        /// 判断是否是合法的QQ号码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsQQ(this string input)
        {
            Regex reg = new Regex(@"^([1-9][0-9]{4,10})$");
            return reg.IsMatch(input);
        }

        /// <summary>
        /// 判断是否是大于0的整数
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsNumber(this string input)
        {
            Regex reg = new Regex(@"^[\d]+$");
            return reg.IsMatch(input);
        }

        /// <summary>
        /// 判断是否是7位到13位数字或-
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsTel(this string input)
        {
            Regex reg = new Regex(@"^[\d\-]{7,13}$");
            return reg.IsMatch(input);
        }


        /// <summary>
        /// 判断是否是合法日期
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsDateTime(this string input)
        {
            try
            {
                Convert.ToDateTime(input);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 是否是ID列表【用逗号分隔】
        /// </summary>
        /// <param name="input"></param>
        /// <param name="span"></param>
        /// <returns></returns>
        public static bool IsIdList(this string input)
        {
            Regex regexObj = new Regex(@"^[0-9]+(,[0-9]+)*$");
            return regexObj.IsMatch(input);
        }



        /// <summary>
        /// 是否存在SQLSERVER关键符号,[ 单引号,空格 ]
        /// </summary>
        /// <param name="recormend"></param>
        /// <returns>true: 存在  false : 不存在 </returns>
        public static bool ExistsSQLKeyChar(this string Par)
        {
            Regex regexObj = new Regex(@"[\'\s]");
            return regexObj.IsMatch(Par);
        }

        /// <summary>
        /// 判断是否是合法的密码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsPassWord(this string input, bool isMD5)
        {
            if (isMD5)
            {
                Regex reg = new Regex(@"^([0-9a-zA-Z]{32})$");
                return reg.IsMatch(input);
            }
            else
            {
                Regex reg = new Regex(@"^([^\s]{6,20})$");
                return reg.IsMatch(input);
            }
        }

        /// <summary>
        /// 判断是否是合法的Email
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsEmail(this string input)
        {
            Regex reg = new Regex(@"^([\w\d\.\-]+@([\w\d\-]+\.)+[\w\d\-]+)$");
            return reg.IsMatch(input);
        }

        /// <summary>
        /// 判断是否是中国邮政编码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsPostCode(this string input)
        {
            Regex reg = new Regex(@"^([\d]{6})$");
            return reg.IsMatch(input);
        }

        /// <summary>
        /// 是否是手机号码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsMobilPhone(this string input)
        {
            Regex reg = new Regex(@"^([\d]{11})$");
            return reg.IsMatch(input);
        }
        /// <summary>
        /// 是否是电话号码  格式  区号-电话号码  或者是 7-8位电话号码 或者是 区号 空格 7-8位电话号码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsTelPhone(this string input)
        {
            Regex reg = new Regex(@"^(([\d]{3,4})?([-\s]?)[\d]{7,8})$");
            return reg.IsMatch(input);
        }

        #endregion

        #region "反序列化"
        public static object DeserializeObject(this string input)
        {
            IFormatter formatter = new BinaryFormatter();
            byte[] byt = Convert.FromBase64String(input);
            object obj = null;
            using (Stream stream = new MemoryStream(byt, 0, byt.Length))
            {
                obj = formatter.Deserialize(stream);
            }
            return obj;
        }

        public static T DeserializeObject<T>(this string input) where T : new()
        {
            return (T)input.DeserializeObject();
        }
        #endregion
    }
}
